package com.clementheliou.cheliou.dal.model.camera.brand.builder;

import org.springframework.util.Assert;

import com.clementheliou.cheliou.dal.dao.camera.brand.CameraBrandDAO;
import com.clementheliou.cheliou.dal.model.camera.brand.CameraBrand;
import com.clementheliou.cheliou.util.builder.ObjectBuilder;

/**
 * Builder used to get {@link CameraBrand} instances for test purpose. It must only be used through
 * one of its static factory methods.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link CameraBrand};
 * @see {@link ObjectBuilder}.
 * @since 1.0
 */
public class CameraBrandBuilder extends ObjectBuilder<CameraBrand> {

	/**
	 * The {@link CameraBrandDAO} to be used to persist the created object if needed.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	private final CameraBrandDAO cameraBrandDAO;

	/**
	 * Private constructor from the {@link CameraBrandDAO} to be used.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @param cameraBrandDAO the {@link CameraBrandDAO} to be used.
	 * @since 1.0
	 */
	private CameraBrandBuilder(CameraBrandDAO cameraBrandDAO) {
		this.cameraBrandDAO = cameraBrandDAO;
	}

	/**
	 * Static factory method used to get a builder instance for a {@link CameraBrand} object that
	 * must be persistent. It's mostly used on data access layer's methods tests.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @param cameraBrandDAO the {@link CameraBrandDAO} to be used.
	 * @return the builder instance to be used.
	 * @since 1.0
	 */
	public static CameraBrandBuilder with(CameraBrandDAO cameraBrandDAO) {
		return new CameraBrandBuilder(cameraBrandDAO);
	}

	/**
	 * Creates a default {@link CameraBrand} instance, ready to be persisted.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @return the builder instance to be used.
	 * @since 1.0
	 */
	public CameraBrandBuilder createDefaultCameraBrand() {
		setInstance(createInstance());
		return this;
	}

	/**
	 * Persists the built {@link CameraBrand} instance then flush the current session.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @return the builder instance after this action.
	 * @since 1.0
	 */
	public CameraBrandBuilder persistAndFlush() {
		Assert.notNull(cameraBrandDAO, "cameraBrandDAO must not be null at this time");

		cameraBrandDAO.saveEntity(getObject());
		cameraBrandDAO.flushSession();
		return this;
	}

	/**
	 * Creates a {@link CameraBrand} instance with default values. These ones have a functional
	 * sense.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @return the built instance.
	 * @since 1.0
	 */
	private CameraBrand createInstance() {
		final CameraBrand defaultCameraBrand = new CameraBrand();
		defaultCameraBrand.setName("Nikon");

		return defaultCameraBrand;
	}
}
